<!--
 * @Author: Anjg
 * @Date: 2025-05-21 23:17:05
 * @LastEditTime: 2025-07-19 23:09:48
 * @Description:
-->
<template>
  <div class="vant-tree">
    <div
      v-for="node in processedData"
      :key="node.id"
      class="vant-tree-node"
    >
      <div class="vant-tree-node-content">
        <span v-if="node.children && node.children.length">
          <van-icon
            :name="node.expanded ? 'arrow-down' : 'arrow'"
            @click="toggleExpand(node)"
          />
        </span>
        <span @click.stop="handleClick(node)">
          {{ node.label }}
        </span>
      </div>
      <div
        v-if="node.expanded && node.children && node.children.length"
        class="vant-tree-node-children"
      >
        <vant-tree
          :data="node.children"
          :level="node.level + 1"
          @node-click="$emit('node-click', $event)"
        />
      </div>
    </div>
  </div>
</template>

<script>
export default {
    name: 'VantTree',
    props: {
        data: Array,
        level: {
            type: Number,
            default: 0
        }
    },
    computed: {
        processedData() {
            return this.processTreeData(this.data);
        }
    },
    methods: {
        processTreeData(nodes, level = 0) {
            return nodes.map((node) => ({
                ...node,
                level,
                expanded: node.expanded || false,
                hasChildren: !!(node.children && node.children.length)
            }));
        },
        toggleExpand(node) {
            if (node.hasChildren) {
                node.expanded = !node.expanded;
                this.$forceUpdate();
            }
        },

        handleClick(node) {
            this.$emit('node-click', node);
        }
    }
};
</script>

<style scoped>
.vant-tree {
    text-align: left;
}

.vant-tree-node {
    padding: 5px 0;
}

.vant-tree-node-content {
    padding: 5px 10px;
    border-radius: 4px;
    display: flex;
    align-items: center;
}

.vant-tree-node-content:hover {
    background-color: red;
    cursor: pointer;
}

.vant-tree-node-children {
    padding-left: 20px;
}
</style>
